package tutor.mina.client;

import java.net.InetSocketAddress;

import javax.net.ssl.SSLContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.common.IoConnector;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.filter.ssl.KeyStoreFactory;
import org.apache.mina.filter.ssl.SslContextFactory;
import org.apache.mina.filter.ssl.SslFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

public class SynchronousStyleSSLTimeClient {

    static Log log = LogFactory.getLog( SynchronousStyleSSLTimeClient.class );

    public static void main( final String[] args ) {
        final IoConnector connector = new NioSocketConnector();

        connector.getSessionConfig().setUseReadOperation( true );

        try {
            final SslFilter sslFilter = new SslFilter( newSSLContext() );
            sslFilter.setUseClientMode( true );

            connector.getFilterChain().addLast( "ssl", sslFilter );
            connector.getFilterChain().addLast( "codec",
                    new ProtocolCodecFilter( new TextLineCodecFactory() ) );
            connector.getFilterChain().addLast( "logging", new LoggingFilter() );

            log.info( connector.connect( new InetSocketAddress( 8151 ) )
                    .awaitUninterruptibly().getSession().read()
                    .awaitUninterruptibly().getMessage() );
        }
        catch( final Exception e ) {
            log.error( "Error:", e );
        }
        finally {
            connector.dispose();
        }
    }

    private static SSLContext newSSLContext()
        throws Exception {
        final KeyStoreFactory trustStoreFactory = new KeyStoreFactory();
        trustStoreFactory.setDataUrl( ClassLoader
                .getSystemResource( "truststore" ) );
        trustStoreFactory.setPassword( "123456" );

        final SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setProtocol( "TLS" );
        sslContextFactory.setTrustManagerFactoryAlgorithm( "SunX509" );
        sslContextFactory.setTrustManagerFactoryKeyStore( trustStoreFactory
                .newInstance() );
        sslContextFactory.setKeyManagerFactoryKeyStorePassword( "123456" );

        return sslContextFactory.newInstance();
    }

}
